package com.irdstudio.efp.esb.api.service.wsd;

import com.alibaba.fastjson.JSON;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.basic.framework.core.util.DateUtility;
import com.irdstudio.basic.framework.redis.redisutil.RedisUtil;
import com.irdstudio.efp.basic.framework.mq.client.producer.MQProducerMessageClient;
import com.irdstudio.efp.basic.framework.mq.constant.TagEnums;
import com.irdstudio.efp.basic.framework.mq.constant.TopicEnums;
import com.irdstudio.efp.esb.api.bean.wsd.credit.req.finalnotice.NlsWsdFinalNoticeReqBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceHandler;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.common.constant.PrdAdaptedSoltEnums;
import com.irdstudio.efp.nls.service.facade.WsApproveackConfirmService;
import com.irdstudio.efp.nls.service.facade.WsApproveackNotifyService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.vo.WsApproveackConfirmVO;
import com.irdstudio.efp.nls.service.vo.WsApproveackNotifyVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.rocketmq.common.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import static com.irdstudio.basic.framework.core.constant.BaseConstant.ADMIN;
import static com.irdstudio.basic.framework.redis.redisutil.keys.Ocm_Nls_Key.RISK_FINAL_APPLY_NOTIFY_INFO_KEY;

/**
 * 需求编号:
 * 问题编号:
 * 开发人员: caoxin
 * 创建日期:2019/7/30
 * 功能描述:
 * 修改日期:2019/7/30
 * 修改描述:
 */
@Service("nlsWsdFinalNoticeProcessServcie")
public class NlsWsdFinalNoticeProcessServcie implements FrameworkService {

    public EsbRespServiceBean processCreditNoticeApply(NlsWsdFinalNoticeReqBean reqWsdCreditNoticeBean, EsbReqServiceBean esbReqServiceBean) throws ESBException {
        try {
            // 查询出对应流水号的授信申请信息
            NlsCreditInfoVO nlsCreditInfoVO = nlsCreditInfoService.queryByLmtApplySeq(reqWsdCreditNoticeBean.getAdptCrdtAplNo());
            if (nlsCreditInfoVO == null) {
                logger.error("授信复审通知【REQUESTID】:+"+reqWsdCreditNoticeBean.getRqsIdmptntID()+" 【APPLYNO】:"+reqWsdCreditNoticeBean.getAdptCrdtAplNo()+" 获取不到授信初审申请信息!!!");
                throw new ESBException(EsbRetCodeStandard.WFJKYWGZ.getValue(),"获取不到授信初审申请信息!!!");
            }
            // 校验是否有复审信息
            WsApproveackNotifyVO wsApproveackNotifyVO = new WsApproveackNotifyVO();
            wsApproveackNotifyVO.setRequestId(reqWsdCreditNoticeBean.getRqsIdmptntID());
            wsApproveackNotifyVO = wsApproveackNotifyService.queryByPk(wsApproveackNotifyVO);

            if (wsApproveackNotifyVO == null){
                logger.error("授信复审通知【REQUESTID】:+"+reqWsdCreditNoticeBean.getRqsIdmptntID()+" 【APPLYNO】:"+reqWsdCreditNoticeBean.getAdptCrdtAplNo()+" 获取不到授信终审申请信息!!!");
                throw new ESBException(EsbRetCodeStandard.WFJKYWGZ.getValue(),"获取不到授信终审申请信息!!!");
            }
            // 设置授信申请信息 插槽阶段和是否通过
            // 来源默认赋值 插槽阶段 1为授信，2位用信
            nlsCreditInfoVO.setSoltStage(PrdAdaptedSoltEnums.SoltStageEnum.CREDIT.getVALUE());
            nlsCreditInfoVO.setRspMsg(reqWsdCreditNoticeBean.getRfsRsn());
            // 将数据插入数据库
            WsApproveackConfirmVO wsApproveackConfirmVO = insertWsApproveackConfirm(reqWsdCreditNoticeBean, nlsCreditInfoVO);
            // 放入消息到redis中
            redis.set(RISK_FINAL_APPLY_NOTIFY_INFO_KEY.getPrefix()+reqWsdCreditNoticeBean.getAdptCrdtAplNo(),JSON.toJSONString(wsApproveackConfirmVO));
            // 发送mq处理
            sendCreditMessageToMq(nlsCreditInfoVO);

        }catch (UnsupportedEncodingException e1){
            e1.printStackTrace();
            logger.error("rocketmq发送异常!!!");
            throw new ESBException(e1);
        }catch (Exception e){
            throw e;
        }
        EsbRespServiceBean esbRespServiceBean = EsbRespServiceHandler.esbSuccessHandler(esbReqServiceBean);
        nlsWsdProcessServcie.setEsbRespServiceBean(reqWsdCreditNoticeBean.getAdptCrdtAplNo(),esbRespServiceBean);
        return esbRespServiceBean;
    }
    /**
     * 需求编号:2019D0910
     * 问题编号:
     * 开发人员: caoxin
     * 创建日期:2019/8/19
     * 功能描述:插入终审通知应答表
     * 修改日期:2019/8/19
     * 修改描述:
     */
    private WsApproveackConfirmVO insertWsApproveackConfirm(NlsWsdFinalNoticeReqBean reqWsdCreditNoticeBean, NlsCreditInfoVO nlsCreditInfoVO) throws ESBException {
        WsApproveackConfirmVO wsApproveackConfirmVO = new WsApproveackConfirmVO();
        wsApproveackConfirmVO.setRequestId(reqWsdCreditNoticeBean.getRqsIdmptntID());
        wsApproveackConfirmVO.setApplyNo(reqWsdCreditNoticeBean.getAdptCrdtAplNo());
        wsApproveackConfirmVO.setCertName(nlsCreditInfoVO.getCusName());
        wsApproveackConfirmVO.setCertNo(nlsCreditInfoVO.getCertCode());
        wsApproveackConfirmVO.setIsAgree(reqWsdCreditNoticeBean.getPassFlg());
        wsApproveackConfirmVO.setRefuseCode(reqWsdCreditNoticeBean.getRfsCd());
        wsApproveackConfirmVO.setAckMsg(reqWsdCreditNoticeBean.getRfsRsn());
        wsApproveackConfirmVO.setCreditAmt(reqWsdCreditNoticeBean.getCrdtRcmndnAmt());
        String currAppDateTimeStr = DateUtility.getCurrAppDateTimeStr();
        wsApproveackConfirmVO.setInputDate(currAppDateTimeStr);
        wsApproveackConfirmVO.setCreateUser(ADMIN);
        wsApproveackConfirmVO.setCreateTime(new Date());
        wsApproveackConfirmVO.setUpdateUser(ADMIN);
        wsApproveackConfirmVO.setUpdateTime(new Date());
        int result = wsApproveackConfirmService.insertWsApproveackConfirm(wsApproveackConfirmVO);
        if (result != 1){
            logger.error("授信复审通知【REQUESTID】:+"+reqWsdCreditNoticeBean.getRqsIdmptntID()+" 【APPLYNO】:"+reqWsdCreditNoticeBean.getAdptCrdtAplNo()+" 插入授信应答信息表失败!!!");
            throw new ESBException(EsbRetCodeStandard.YWLJCLYC.getValue(),"插入授信应答信息表失败!!!");
        }
        return wsApproveackConfirmVO;
    }

    private void sendCreditMessageToMq(NlsCreditInfoVO nlsCreditInfoVO) throws UnsupportedEncodingException {
        // 投递授信信息进入插槽处理
        producerService.sendMsg(new Message(TopicEnums.QUEUE_TASK_CREDIT_TOPIC.getTopicId(),
                TagEnums.TAG_QUEUE_CREDIT_TASK.getTagId(),
                nlsCreditInfoVO.getLmtApplySeq(),
                JSON.toJSONString(nlsCreditInfoVO).getBytes("UTF-8")));
    }
    // 日志信息
    private static final Logger logger = LoggerFactory.getLogger(NlsWsdFinalNoticeProcessServcie.class);


    /**
     * 消息队列服务
     */
    @Autowired
    @Qualifier("producerService")
    private MQProducerMessageClient producerService;

    /**
     * 网商贷服务
     */
    @Autowired
    private NlsWsdProcessServcie nlsWsdProcessServcie;

    /**
     * 授信申请服务
     */
    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

    /**
     * 授信申请应答表
     */
    @Autowired
    @Qualifier("wsApproveackConfirmService")
    private WsApproveackConfirmService wsApproveackConfirmService;

    /**
     * redis
     */
    @Autowired
    RedisUtil redis;

    /**
     * 授信复审信息
     */
    @Autowired
    @Qualifier("wsApproveackNotifyService")
    private WsApproveackNotifyService wsApproveackNotifyService;

}
